
// pages/tags/index.js
const { tagManager } = require('../../utils/cloud')
const { toast, dialog, errorHandler } = require('../../utils/uiHelper')

const app = getApp()

Page({
  data: {
    tags: [],
    newTagName: '',
    newTagColor: '#4A90E2',
    editingTag: null,
    colors: [
      '#4A90E2',
      '#50B347',
      '#E6A23C',
      '#F56C6C',
      '#909399',
      '#9C27B0',
      '#FF5722',
      '#795548'
    ],
    isLoading: false,
    isSubmitting: false
  },

  onLoad: async function() {
    // 检查登录状态
    if (!app.checkLogin()) {
      wx.navigateBack()
      return
    }

    await this.loadTags()
  },

  onPullDownRefresh: async function() {
    await this.loadTags()
    wx.stopPullDownRefresh()
  },

  // 加载标签列表
  async loadTags() {
    try {
      this.setData({ isLoading: true })
      toast.loading('加载中...')

      const result = await tagManager.listTags()
      
      if (result.code === 0) {
        // 如果没有标签，初始化默认标签
        if (result.data.length === 0) {
          const initResult = await tagManager.initDefaultTags()
          if (initResult.code === 0) {
            this.setData({ tags: initResult.data })
          }
        } else {
          this.setData({ tags: result.data })
        }
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '加载标签失败')
    } finally {
      this.setData({ isLoading: false })
      toast.hideLoading()
    }
  },

  // 输入新标签名称
  onInputNewTag: function(e) {
    this.setData({
      newTagName: e.detail.value
    })
  },

  // 输入编辑标签名称
  onInputEditTag: function(e) {
    this.setData({
      'editingTag.name': e.detail.value
    })
  },

  // 选择标签颜色
  onSelectColor: function(e) {
    const color = e.currentTarget.dataset.color
    if (this.data.editingTag) {
      this.setData({
        'editingTag.color': color
      })
    } else {
      this.setData({
        newTagColor: color
      })
    }
  },

  // 验证标签名称
  validateTagName: function(name, excludeId = '') {
    if (!name.trim()) {
      toast.info('请输入标签名称')
      return false
    }

    // 检查是否已存在相同名称的标签
    const exists = this.data.tags.some(tag => 
      tag.name === name.trim() && tag._id !== excludeId
    )
    
    if (exists) {
      toast.info('标签名称已存在')
      return false
    }

    return true
  },

  // 添加新标签
  async onAddTag() {
    try {
      const { newTagName, newTagColor } = this.data
      
      // 验证标签名称
      if (!this.validateTagName(newTagName)) return

      this.setData({ isSubmitting: true })
      toast.loading('创建中...')

      const result = await tagManager.createTag({
        name: newTagName.trim(),
        color: newTagColor
      })

      if (result.code === 0) {
        // 更新本地数据
        this.setData({
          tags: [...this.data.tags, result.data],
          newTagName: '',
          newTagColor: '#4A90E2'
        })
        toast.success('创建成功')
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '创建标签失败')
    } finally {
      this.setData({ isSubmitting: false })
      toast.hideLoading()
    }
  },

  // 开始编辑标签
  onStartEdit: function(e) {
    const { tag } = e.currentTarget.dataset
    this.setData({
      editingTag: { ...tag }
    })
  },

  // 取消编辑
  onCancelEdit: function() {
    this.setData({
      editingTag: null
    })
  },

  // 保存编辑的标签
  async onSaveEdit() {
    try {
      const { editingTag } = this.data
      
      // 验证标签名称
      if (!this.validateTagName(editingTag.name, editingTag._id)) return

      this.setData({ isSubmitting: true })
      toast.loading('保存中...')

      const result = await tagManager.updateTag(editingTag)

      if (result.code === 0) {
        // 更新本地数据
        const newTags = this.data.tags.map(tag => 
          tag._id === editingTag._id ? editingTag : tag
        )
        this.setData({
          tags: newTags,
          editingTag: null
        })
        toast.success('保存成功')
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '保存标签失败')
    } finally {
      this.setData({ isSubmitting: false })
      toast.hideLoading()
    }
  },

  // 删除标签
  async onDeleteTag(e) {
    try {
      const { tag } = e.currentTarget.dataset
      
      if (tag.isDefault) {
        toast.info('默认标签不能删除')
        return
      }

      const confirmed = await dialog.confirm('确定要删除这个标签吗？', '删除标签')
      if (!confirmed) return

      toast.loading('删除中...')
      const result = await tagManager.deleteTag(tag._id)

      if (result.code === 0) {
        // 更新本地数据
        const newTags = this.data.tags.filter(t => t._id !== tag._id)
        this.setData({ tags: newTags })
        toast.success('删除成功')
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '删除标签失败')
    } finally {
      toast.hideLoading()
    }
  }
})